<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/9/5
 * Time: 17:29
 */

namespace App\Libraries\Weapp;


use JiaweiXS\WeApp\WeApp;

class WeappLib
{

    public static $appid = 'wx1fe0b05d652539d2';

    public static $appsercert = '8aebce86b72a73a17c8b6140006f9058';

    public static function getSessionKey($code)
    {
        $weapp = new WeApp(self::$appid,self::$appsercert,'../storage/cache/');
        $session_key = $weapp->getSessionKey($code);
        $result = json_decode($session_key,true);
        if(array_key_exists('errcode',$result)){
            throw new \Exception('获取session_key失败');
        }
        return $result;
    }

    public static function decryptData($sessionKey,$iv,$data)
    {
        if (strlen($sessionKey) != 24) {
            throw new \Exception('encodingAesKey 非法');
        }
        $aesKey=base64_decode($sessionKey);

        if (strlen($iv) != 24) {
            throw new \Exception('-41002');
        }
        $aesIV=base64_decode($iv);

        $aesCipher=base64_decode($data);

        $result=openssl_decrypt( $aesCipher, "AES-128-CBC", $aesKey, 1, $aesIV);

        $dataObj=json_decode( $result );

        if( $dataObj  == NULL )
        {
            throw new \Exception('aes 解密失败');
        }
        if( $dataObj->watermark->appid != self::$appid)
        {
            throw new \Exception('解密后得到的buffer非法');
        }
        $data = json_decode($result,true);
        return $data;
    }
}